package com.shop.shopserver.aspect;


import com.shop.shopcommon.constant.InsertConstant;
import com.shop.shopcommon.enumeration.OperationType;
import com.shop.shopserver.annotation.InsertCreateTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class InsertCreateTimeAspect {

    @Pointcut("@annotation(com.shop.shopserver.annotation.InsertCreateTime)")
        public void setCreateTimePointcut(){}
    @Before("setCreateTimePointcut()")
    public void insertAspect(JoinPoint joinPoint) {
        log.info("开始进行公共字段自动填充");

        //获取到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();// 方法签名对象
        InsertCreateTime insertCreateTime=signature.getMethod().getAnnotation(InsertCreateTime.class); // 获取方法上的注解对象
        OperationType operationType = insertCreateTime.value();//获取数据库操作类型

        //获取到当前被拦截的方法的参数--实体对象
        Object[] args = joinPoint.getArgs();
        if (args== null ||args.length == 0){
            return;
        }

        Object entity= args[0];//约定实体类在参数列表中位于第一位

        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();

        //根据当前不同的操作类型，为对应的属性通过反射来赋值
        if (operationType==OperationType.INSERT){
            try {
                //获取赋值方法
                Method setCreateTime = entity.getClass().getDeclaredMethod(InsertConstant.SET_CREATE_TIME, LocalDateTime.class);
                //通过反射为对象赋值
                setCreateTime.invoke(entity,now);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
